package org.epidroid.epidroid.androsoul.engine.contacts;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.epidroid.epidroid.androsoul.engine.AndroSoul;

public class Contacts implements Serializable {

	private static final long serialVersionUID = 1403661395799953090L;
	private List<ContactGroup> _groups = null;
	private transient AndroSoul _androsoul = null;

	public Contacts(AndroSoul androsoul) {
		_androsoul = androsoul;
		_groups = new ArrayList<ContactGroup>();
	}

	public List<ContactGroup> getGroups() {
		return _groups;
	}

	public void setGroups(List<ContactGroup> mGroups) {
		this._groups = mGroups;
	}

	public Iterator<ContactGroup> iterator() {
		return _groups.iterator();
	}

	/**
	 * Add a group by its name
	 * 
	 * @param name
	 *            name of the group to be added
	 * @return new added group or null if the group already exists
	 */
	public ContactGroup addGroup(String name) {
		// Check that a group with the same name does not already exists
		Iterator<ContactGroup> it = iterator();
		while (it.hasNext()) {
			if (it.next().getName().equals(name))
				return null;
		}
		ContactGroup group = new ContactGroup(_androsoul, name);
		_groups.add(group);
		return group;
	}

	/**
	 * Add a contact group
	 * 
	 * @param group
	 *            group to be added
	 */
	public void addGroup(ContactGroup group) {
		_groups.add(group);
	}

	/**
	 * Add a contact to a group
	 * 
	 * @param name
	 *            name of the contact to be added
	 * @param group
	 *            Group in which to add the contact (if null, do not add in a
	 *            group)
	 * @return Contact that has been added (created if does not exists)
	 */
	public NetsoulContact addContact(String name, ContactGroup group) {
		if (group != null) {
			return group.add(name);
		}
		return _androsoul.getDictionary().createContact(name);
	}

	/**
	 * Find an existing group of contacts
	 * 
	 * @param name
	 *            name of the group
	 * @return Group found or null if not found
	 */
	public ContactGroup findGroup(String name) {
		Iterator<ContactGroup> it = _groups.iterator();
		while (it.hasNext()) {
			ContactGroup tmp = it.next();
			if (tmp.getName().equals(name))
				return tmp;
		}
		return null;
	}

	public boolean isEmpty() {
		return _groups.isEmpty();
	}

	/**
	 * Clear the contacts
	 */
	public void clear() {
		_groups.clear();
	}
}
